import { app, protocol, BrowserWindow, Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
import Store from "electron-store"
import { updateTicketInterval} from '@/utils/ticket'
// 数据持久化
const store = new Store() 
const {
	handleUpdate
} = require('./utils/handleUpdate')
const { ipcMain, shell, dialog } = require('electron')
    // const path = require('path')
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    { scheme: 'app', privileges: { secure: true, standard: true } }
])
let win
let tray = null
async function createWindow() {
    let size = require('electron').screen.getPrimaryDisplay().workAreaSize
    let width = parseInt(size.width)
    Menu.setApplicationMenu(null)
        // Create the browser window.
    win = new BrowserWindow({
            icon: './public/favicon.ico',
            width: 1260,
            height: 720,
            minWidth: 1260,
            minHeight: 720,
            webPreferences: {
                devTools: true,
                // Use pluginOptions.nodeIntegration, leave this alone
                // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
                nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
                contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
                webSecurity: false
            },
            title: '小熊抢外观'
        })
        // 关闭默认菜单
    if (isDevelopment) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
            // Load the index.html when not in development
        win.loadURL('app://./index.html')
            // win.webContents.openDevTools()
    }
    handleUpdate(win, "http://wbl.hifuncat.com/app_version/xiaoxiong-1.0.0.dmg")
}
//从渲染进程传递过来的值
ipcMain.on('setStore', (_, key, value) => {
    store.set(key, value)
    if('ticketList' == key && value){
        updateTicketInterval(JSON.parse(value),store, key);
    }
  })
  ipcMain.on('get-data', (event, key) => {
    event.returnValue = store.get(key)
  })
app.setAppUserModelId('xiaoxiong')
// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async() => {
    // if (isDevelopment && !process.env.IS_TEST) {
    //     // Install Vue Devtools
    //     try {
    //         await installExtension(VUEJS3_DEVTOOLS)
    //     } catch (e) {
    //         console.error('Vue Devtools failed to install:', e.toString())
    //     }
    // }
    // 打包调试
    // globalShortcut.register('CommandOrControl+Shift+L', () => {
    //     let focusWin = BrowserWindow.getFocusedWindow()
    //     focusWin && focusWin.toggleDevTools()
    // })
    createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}
ipcMain.on('download', (event, args, webContents) => {
    //下面这句会触发will-download事件
    win.webContents.downloadURL(args)
        // 下载触发
    win.webContents.session.on('will-download', (event, item, webContent) => {
        //设置文件存放位置，如果用户没有设置保存路径，Electron将使用默认方式来确定保存路径（通常会提示保存对话框）
        // item.setSavePath('niaho')
        item.setSaveDialogOptions({
            defaultPath: webContents
        })
        item.on('updated', (event, state) => {
            if (state === 'interrupted') {} else if (state === 'progressing') {
                if (item.isPaused()) {} else {}
            }
        })
        item.once('done', (event, state) => {
            if (state === 'completed') {
                //回显 调用渲染进程方法
                win.webContents.send('downstate', state)
            } else {
                //回显 调用渲染进程方法
                win.webContents.send('downstate', state)
            }
        })
    })
})